import React, {Component} from 'react';
import {Layout, List, Icon, Input, Button, Modal, message} from "antd";
import '../statics/iconfont/iconfont.css'
import {URL, MessageBoardConstant} from "../../src/constant/Constant"
import {Link, hashHistory} from 'react-router';

const {Header, Content, Footer,} = Layout;


// const testUrl = 'http://127.0.0.1:8080/messageBoard/getAllMessage'

class MessageBoard extends Component {//留言板

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            messageData: [{}],//留言信息
            leaveMessage: "",//留言输入框的内容
            commentMessage: "",//评论框的内容
            //当前点击的评论者的关键信息
            toUserId: -1,
            toNickName: "",
            commentId: "",
            messageDataItem: {},//一条评论的信息，是messageData的一条数据
        }
    }

    showModal = (event, userId, nickName, commentId, item) => {

        this.setState({
            visible: true,
            toUserId: userId,
            nickName: nickName,
            commentId: commentId,
            messageDataItem: item
        });
    };

    //用于提交对某用户的评论
    handleOk = (event, index) => {
        const toId = this.state.toUserId;
        const url = URL.urlRoot + URL.addMessage;
        console.log(url)
        const formData = new FormData();
        formData.append('commentId', this.state.commentId);
        formData.append('fromId', window.localStorage.id);//获取当前的用户id
        formData.append('fromUser', window.localStorage.username);
        formData.append('toUser', this.state.toNickName);
        formData.append('toId', toId.toString());
        formData.append('content', this.state.commentMessage);
        formData.append("flag","0");
        fetch(url, {
            method: 'POST',
            body: formData,
        }).then(res => {
            return res.json();
        }).then(res => {
            if (res.code === 0) {
                message.info("留言成功");
                this.setState({
                    messageData: res.data,
                })
            }
        })


        this.setState({
            visible: false,
        });
    };

    handleCancel = e => {
        console.log(e);
        this.setState({
            visible: false,
        });
    };

    //处理留言提交事件
    handleLeaveMessageOnClick() {
        const date = new Date();
        const toId = MessageBoardConstant.toId;
        const url = URL.urlRoot + URL.addMessage;
        console.log(url)
        const formData = new FormData();
        formData.append('commentId', date.getTime().toString());
        formData.append('fromId', window.localStorage.id);//获取当前的用户id
        formData.append('fromUser', window.localStorage.username);
        formData.append('toUser', "留言板(虚拟对象)");
        formData.append('toId', toId.toString());
        formData.append('content', this.state.leaveMessage);
        formData.append("flag","0")
        fetch(url, {
            method: 'POST',
            body: formData,
        }).then(res => {
            return res.json();
        }).then(res => {
            if (res.code === 0) {
                message.info("留言成功");
                this.setState({
                    messageData: res.data,
                    leaveMessage: ""
                })
            }
        })
    }

    /**
     *
     * @param value
     * @param flag 0 代表留言，1代表评论
     */
    handleChangeTextArea(value, flag) {

        if (flag) {//评论
            this.setState({
                commentMessage: value
            });
        } else {//留言
            this.setState({
                leaveMessage: value
            });
        }

    }
    handleExit=()=>{
        window.location.href="";
    }
    componentWillMount() {
        //获取留言模块的留言信息
        this.getMessageBoards();
    }


    //获取留言模块的留言信息
    getMessageBoards() {
        //http://127.0.0.1:8080/springbootjpacementv4_1_war/messageBoard/getAllMessage'
        //'http://127.0.0.1:8080/messageBoard/getAllMessage'
        //URL.urlRoot+URL.getAllMessage
        fetch(URL.urlRoot+URL.getAllMessage, {
            method: 'GET',
        }).then(res => {
            return res.json();
        }).then(res => {
            if (res.code === 0) {
                console.log(res)
                this.setState({
                    messageData: res.data
                })
            }
        })//end then
    }


    render() {


        console.log(this.state.messageData)
        const {TextArea} = Input;
        const IconText = ({type, text, userId, nickName, commentId, item}) => (
            <span>
             <Icon
                 onClick={(event) => this.showModal(event, userId, nickName, commentId, item)}
                 type={type} style={{marginRight: 8}}
             />
                {text}
            </span>
        );
        return (
            <Layout>
                <Header style={{background: '#fff', padding: 0}}>
                    <div className="head_right">
                        <img src={require("../img/logo-whut.png")}/>
                    </div>
                </Header>
                <Content style={{margin: '1%', overflow: 'auto'}}>
                    <div style={{padding: 24, background: '#fff', height: '100%'}}>
                        <div style={{
                            height: '100%'
                        }}>
                            <div
                                id={'rightmenu'}
                                style={{
                                    width: '100%'
                                }}>
                                <h1 style={{textAlign: 'center', marginBottom: '20px'}}>技术交流</h1>


                                <List
                                    itemLayout="vertical"
                                    size="large"
                                    pagination={{
                                        onChange: page => {
                                            console.log(page);
                                        },
                                        pageSize: 5,
                                    }}
                                    dataSource={this.state.messageData}


                                    renderItem={item => (

                                        <List.Item

                                            key={item.userId}
                                            actions={[
                                                <IconText type="message"
                                                          text={item.msgNum}
                                                          userId={item.userId}
                                                          nickName={item.nickName}
                                                          commentId={item.commentId}
                                                          item={item}/>,
                                            ]}
                                        >
                                            <List.Item.Meta
                                                title={
                                                    <a>
                                                        留言者 :{item.nickName}</a>}
                                                description={item.time}
                                            />
                                            <div>
                                                <Link to={{
                                                    pathname: "/messageDetail",
                                                    state: this.state.messageData,
                                                    query: {
                                                        index: item.index
                                                    }
                                                }}>{item.content}</Link>
                                            </div>

                                        </List.Item>
                                    )}
                                />,
                            </div>
                        </div>
                    </div>


                    <Modal
                        title="评论"
                        visible={this.state.visible}
                        onOk={(event) => this.handleOk(event)}
                        onCancel={this.handleCancel}
                    >
                        <TextArea
                            onBlur={(event => this.handleChangeTextArea(event.target.value, 1))}//评论
                            id={'reply'}
                            placeholder="输入内容,拖动右下角可以放大"
                            autosize={{minRows: 4, maxRows: 8}}
                        />
                    </Modal>
                </Content>
                {/*底部评论模块*/}
                <div style={{padding: 14, background: '#fff', height: '30%'}}>
                    <TextArea
                        defaultValue={""}
                        value={this.state.leaveMessage}
                        onChange={(event => this.handleChangeTextArea(event.target.value, 0))}//留言
                        placeholder="输入内容,拖动右下角可以放大"
                        autosize={{minRows: 4, maxRows: 8}}
                    />
                    <Button type={'primary'} size={"large"} htmlType={"button"}
                            onClick={event => {
                                this.handleLeaveMessageOnClick();//处理留言
                            }}
                            style={{
                                float: 'right',
                                margin: '20px 5px 0px 5px'
                            }}
                    >{"提交"}</Button>
                    <Button type={'primary'} size={"large"} htmlType={"button"}
                            onClick={event => {
                                this.handleExit();//处理留言
                            }}
                            style={{
                                float: 'right',
                                margin: '20px 5px 0px 5px'
                            }}
                    >{"退出"}</Button>
                </div>
                <Footer style={{textAlign: 'center', color: 'white', backgroundColor: 'black'}}>
                    SmartLab Design ©2018 Powered By 武汉理工大学智能技术实验室
                </Footer>
            </Layout>

        );
    }
}

export default MessageBoard;